package org.jeecg.modules.login.api;

import com.aliyun.dingtalkcontact_1_0.models.GetUserResponseBody;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.login.LoginService;
import org.jeecg.modules.login.handler.ding.DingHandler;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * [钉钉] 扫码登录
 *
 * @author tianyi.jiang
 * @since 1.2.2
 */
@RestController
@RequestMapping("/sys/ding")
@ConditionalOnExpression("'${basicplatform.login.ding-qr.enable:false}'.equals('true')")
public class DingQrLogin {

    private final DingHandler dingHandler;

    private final DingHandler.DingProperty dingProperty;

    private final LoginService loginService;

    @GetMapping("/auth/parameter")
    public Result<?> parameter() {
        Map<String, String> map = new HashMap<String, String>(2) {{
            this.put("redirectUri", dingProperty.getAuthUrl());
            this.put("clientId", dingProperty.getAppKey());
        }};
        return Result.OK(map);
    }

    @GetMapping("/auth")
    public Result<?> dingLogin(@RequestParam("authCode") String authCode) {
        GetUserResponseBody userResponseBody = dingHandler.dingUser(authCode);
        String mobile = userResponseBody.getMobile();
        return loginService.authByMobile(mobile);
    }

    public DingQrLogin(DingHandler dingHandler, DingHandler.DingProperty dingProperty, LoginService loginService) {
        this.dingHandler = dingHandler;
        this.dingProperty = dingProperty;
        this.loginService = loginService;
    }
}
